use anyhow::Result;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use uuid::Uuid;

use shared::types::Session;

pub struct SessionManager {
    active_sessions: Arc<RwLock<HashMap<String, Session>>>,
}

impl SessionManager {
    pub fn new() -> Self {
        Self {
            active_sessions: Arc::new(RwLock::new(HashMap::new())),
        }
    }
    
    pub async fn create_session(&self, user_id: i64, client_ip: String) -> Result<Session> {
        let session_token = Self::generate_session_token();
        
        let session = Session {
            id: 0, // 将由数据库分配
            user_id,
            session_token: session_token.clone(),
            client_ip,
            client_port: 0, // 将在连接时设置
            data_port: None,
            passive_port: None,
            transfer_mode: shared::types::TransferMode::Passive,
            current_directory: "/".to_string(),
            created_at: chrono::Utc::now(),
            last_activity: chrono::Utc::now(),
            is_active: true,
        };
        
        // 缓存到内存
        self.active_sessions.write().await.insert(session_token, session.clone());
        
        Ok(session)
    }
    
    pub async fn validate_session(&self, token: &str) -> Result<Option<Session>> {
        // 先从缓存查找
        if let Some(session) = self.active_sessions.read().await.get(token) {
            if session.is_active && Self::is_session_valid(session) {
                return Ok(Some(session.clone()));
            }
        }
        
        Ok(None)
    }
    
    fn is_session_valid(session: &Session) -> bool {
        let now = chrono::Utc::now();
        let timeout = chrono::Duration::hours(1); // 1小时超时
        
        now.signed_duration_since(session.last_activity) < timeout
    }
    
    fn generate_session_token() -> String {
        Uuid::new_v4().to_string()
    }
}
